package com.offics.loan.interfaces.controller;

import com.offics.loan.application.dto.loan.*;
import com.offics.loan.application.service.LoanApplicationService;
import com.offics.loan.infrastructure.common.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 贷款控制器
 */
@Tag(name = "贷款", description = "贷款相关接口")
@RestController
@RequestMapping("/api/loans")
@RequiredArgsConstructor
@SecurityRequirement(name = "JWT")
public class LoanController {

    private final LoanApplicationService loanApplicationService;

    /**
     * 申请贷款
     *
     * @param request 贷款申请请求
     * @return 贷款申请响应
     */
    @Operation(summary = "申请贷款", description = "申请贷款")
    @PostMapping("/apply")
    public Result<LoanApplyResponse> applyLoan(@Valid @RequestBody LoanApplyRequest request) {
        LoanApplyResponse response = loanApplicationService.applyLoan(request);
        return Result.success(response);
    }

    /**
     * 取消贷款申请
     *
     * @param id 贷款ID
     * @return 是否成功
     */
    @Operation(summary = "取消贷款申请", description = "取消贷款申请")
    @PutMapping("/{id}/cancel")
    public Result<Void> cancelLoan(@PathVariable Long id) {
        boolean result = loanApplicationService.cancelLoan(id);
        return result ? Result.success() : Result.failure("取消贷款申请失败");
    }

    /**
     * 获取用户的贷款列表
     *
     * @param userId 用户ID
     * @return 贷款列表
     */
    @Operation(summary = "获取用户的贷款列表", description = "获取用户的贷款列表")
    @GetMapping("/user/{userId}")
    public Result<List<LoanDetailResponse>> getLoanList(@PathVariable Long userId) {
        List<LoanDetailResponse> responses = loanApplicationService.getLoanList(userId);
        return Result.success(responses);
    }

    /**
     * 获取贷款详情
     *
     * @param id 贷款ID
     * @return 贷款详情
     */
    @Operation(summary = "获取贷款详情", description = "获取贷款详情")
    @GetMapping("/{id}")
    public Result<LoanDetailResponse> getLoanDetail(@PathVariable Long id) {
        LoanDetailResponse response = loanApplicationService.getLoanDetail(id);
        return Result.success(response);
    }

    /**
     * 计算贷款
     *
     * @param request 贷款计算请求
     * @return 贷款计算响应
     */
    @Operation(summary = "计算贷款", description = "计算贷款")
    @PostMapping("/calculate")
    public Result<LoanCalculateResponse> calculateLoan(@Valid @RequestBody LoanCalculateRequest request) {
        LoanCalculateResponse response = loanApplicationService.calculateLoan(request);
        return Result.success(response);
    }
}
